package com.modemMgr.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.modemMgr.util.DBAccessor;
import com.modemMgr.util.Pager;
import com.modemMgr.vo.ItemFlow;

public class ItemFlowDAO extends BaseDAO {
	public ItemFlowDAO(DBAccessor dbAccessor) {
		super(dbAccessor);
	}

	public void addItemFlow(String flowType, int sourceId, int distId,
			int item_id, int quantity, String status) throws SQLException {
		String sql = "insert into item_flow(flow_type, source_id, dest_id, item_id, quantity, status) values(?, ?, ?, ?, ?, ?)";
		Object[] params = new Object[] { flowType, sourceId, distId, item_id,
				quantity, status };
		dbAccessor.update(sql, params);
	}

	public ItemFlow getItemFlowById(int flowId) throws Exception {
		String sql = "select * from item_flow where flow_id = ?";
		return dbAccessor.queryObject(ItemFlow.class, sql,
				new Object[] { flowId });
	}

	public List<ItemFlow> getItemFlowList(Pager pager) throws Exception {
		String sql = "select f.*, i.item_name as itemName from item_flow f, items i where f.item_id = i.item_id";
		List<Object> list = new ArrayList<Object>();
		Map<String, Object> params = pager.getParams();

		if (null != params.get("destId")) {
			sql += " and f.dest_id = ?";
			list.add(params.get("destId"));
		}

		if (null != params.get("itemId")) {
			sql += " and f.item_id = ?";
			list.add(params.get("itemId"));
		}

		if (null != params.get("itemTypeId")) {
			sql += " and i.item_type_id = ?";
			list.add(params.get("itemTypeId"));
		}

		if (null != params.get("status")) {
			sql += " and f.status = ?";
			list.add(params.get("status"));
		}

		return dbAccessor.queryList(pager, ItemFlow.class, sql, list.toArray());
	}

	public void removeItemFlowById(int flowId) throws Exception {
		String sql = "delete from item_flow where flow_id = ?";
		dbAccessor.update(sql, new Object[] { flowId });
	}
}
